package com.qkhero.api.controller;

import com.qkhero.api.builder.RequestBuilder;
import com.qkhero.api.builder.RequestBuilderResolver;
import com.qkhero.api.response.ServerErrorResponse;
import com.qkhero.core.common.handler.RequestHandler;
import com.qkhero.core.common.request.Request;
import com.qkhero.core.common.resolver.RequestHandlerResolver;
import com.qkhero.core.common.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一请求处理
 * <p>
 * Created by zhengwei on 2017/4/16.
 */
@RestController
public class ApiController extends BaseController {

    @Autowired
    private RequestBuilderResolver requestBuilderResolver;

    @Autowired
    private RequestHandlerResolver requestHandlerResolver;

    @RequestMapping("router/rest")
    public Response acceptRequest(@RequestParam("apiName") String apiName, HttpServletRequest servletRequest) {

        try {
            RequestBuilder requestBuilder = requestBuilderResolver.resolve(apiName);

            Request bizRequest = requestBuilder.build(servletRequest);

            RequestHandler requestHandler = requestHandlerResolver.resolve(bizRequest);

            Response res = requestHandler.handle(bizRequest);

            return res;
        } catch (Exception e) {
            logger.error("server error, apiName=" + apiName, e);
            return ServerErrorResponse.SERVER_ERROR_RESPONSE;
        }

    }

}
